/**
 * Copyright 2006 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.ocean.server;

import java.util.Map;

import org.apache.lucene.document.Fieldable;
import org.apache.ocean.IndexSchema;

public class LongFieldType extends FieldType {
  public LongFieldType() {
    typeName = "long";
  }
  
  protected void init(IndexSchema schema, Map<String,String> args) {
  }
  
  public static long fromPayload(byte[] readBuffer) {
  	return (((long)readBuffer[0] << 56) +
        ((long)(readBuffer[1] & 255) << 48) +
        ((long)(readBuffer[2] & 255) << 40) +
        ((long)(readBuffer[3] & 255) << 32) +
        ((long)(readBuffer[4] & 255) << 24) +
        ((readBuffer[5] & 255) << 16) +
        ((readBuffer[6] & 255) <<  8) +
        ((readBuffer[7] & 255) <<  0));
  }
  
  public byte[] toPayload(String string) {
  	return toBytes(Long.parseLong(string));
  }
  
  public static byte[] toBytes(long v) {
  	byte[] writeBuffer = new byte[8];
  	writeBuffer[0] = (byte)(v >>> 56);
    writeBuffer[1] = (byte)(v >>> 48);
    writeBuffer[2] = (byte)(v >>> 40);
    writeBuffer[3] = (byte)(v >>> 32);
    writeBuffer[4] = (byte)(v >>> 24);
    writeBuffer[5] = (byte)(v >>> 16);
    writeBuffer[6] = (byte)(v >>>  8);
    writeBuffer[7] = (byte)(v >>>  0);
    return writeBuffer;
  }
  
  public String toInternal(String val) {
    return NumberUtils.long2sortableStr(val);
  }

  public String indexedToReadable(String indexedForm) {
    return NumberUtils.sortableStr2long(indexedForm);
  }

  public String toExternal(Fieldable f) {
    return indexedToReadable(f.stringValue());
  }
}

